package com.aaa.dao.impl;

import com.aaa.ann.ColunmAnn;
import com.aaa.ann.TableAnn;
import com.aaa.dao.MyDao;
import com.aaa.entity.Dept;
import com.aaa.reflect.Person;
import com.aaa.utils.BaseDao;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/8/19 10:47
 * @description：我的通用dao实现类
 * @modified By：
 * @version: 1.0
 */
public class MyDaoImpl<T>  implements MyDao<T> {

    public void saveEntity(T obj) throws Exception {
        Class<?> clazz = obj.getClass();
        //获取表名
        TableAnn tableAnn = clazz.getAnnotation(TableAnn.class);
        String tableName = tableAnn.tableName();
        //获取所有的列名
        StringBuffer colNames = new StringBuffer();
        //获取所有的列值
        List<Object> colValues= new ArrayList<Object>();
            //获取所有的属性
        Field[] fields = clazz.getDeclaredFields();
            //遍历所有的属性
        for (Field field : fields) {
            ColunmAnn colunmAnn = field.getAnnotation(ColunmAnn.class);
            //获取列名
            String colName = colunmAnn.colName();
            colNames.append(colName);
            colNames.append(",");
            //获取列值
            field.setAccessible(true);
            Object colValue = field.get(obj);
            //
            colValues.add("'"+colValue+"'");
        }
        //去掉最后一个逗号  10  0-9,,colNames.length()-1最后一个字符的下标
        colNames.deleteCharAt(colNames.length()-1);
        //拼接sql   insert into tbl_person (colName1,colName2)  values ();
        StringBuffer sql= new StringBuffer(" insert into ");
        sql.append(tableName);
        sql.append(" ( ").append(colNames).append(" ) values ( ");
        sql.append(colValues).append(" ) ");
        //执行sql
        BaseDao baseDao = new BaseDao();
        Connection connection = baseDao.getConnection();
        String toString = sql.toString().replace("[","").replace("]","");
        System.out.println(toString);
        PreparedStatement preparedStatement = connection.prepareStatement(toString);
        int i = preparedStatement.executeUpdate();
        if(i>0){
            System.out.println("操作成功");
        }else
        {
            System.out.println("操作失败");
        }
    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description:返回一个集合封装所有实体类
     * @create time: 2022/8/20 9:30
     * @param clazz
     * @return java.util.List<T>
     */
    public List<T> queryAll(Class<T> clazz) throws Exception {
        List<T> list= new ArrayList<T>();
        //获取表名
        TableAnn tableAnn = clazz.getAnnotation(TableAnn.class);
        String tableName = tableAnn.tableName();
        //获取所有的列名
        StringBuffer colNames = new StringBuffer();
        //获取所有的属性
        Field[] fields = clazz.getDeclaredFields();
        //key 是 列名，value 是属性
        Map<String ,Field> stringFieldMap = new HashMap();
        //遍历所有的属性
        for (Field field : fields) {
            ColunmAnn colunmAnn = field.getAnnotation(ColunmAnn.class);
            //获取列名
            String colName = colunmAnn.colName();
            colNames.append(colName);
            stringFieldMap.put(colName,field);
            colNames.append(",");
        }
        //去掉最后一个逗号
        colNames.deleteCharAt(colNames.length()-1);
        //拼写sql语句
        StringBuffer sqlStringBuffer=new StringBuffer("select "+ colNames+ " from "+ tableName);
        //执行sql
        BaseDao baseDao = new BaseDao();
        Connection connection = baseDao.getConnection();
        PreparedStatement ps = connection.prepareStatement(sqlStringBuffer.toString());
        //获取结果集
        ResultSet resultSet = ps.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        //遍历每一行数据
        while (resultSet.next()){
            //实例化一个空对象
            T obj = (T) clazz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount() ; i++) {
               //依次给obj中所有的属性设置值
                String columnName = metaData.getColumnName(i);
                //返回所有的列名的set集合
                Set<String> keySet = stringFieldMap.keySet();
                //如果属性上面的注解（列名）包含此列名，就操作此属性
                if(keySet.contains(columnName)){
                    //根据列名获取属性
                    Field field = stringFieldMap.get(columnName);
                    field.setAccessible(true);
                    //将列值设置到属性值上
                    field.set(obj,resultSet.getObject(i));
                }

            }
            //将封装好的一个obj封装到list集合中
            list.add(obj);
        }

        return list;
    }

    public static void main(String[] args) throws Exception {
      /*  MyDao<Dept> deptMyDao = new MyDaoImpl<Dept>();
        List<Dept> deptList = deptMyDao.queryAll(Dept.class);
        for (Dept dept : deptList) {
            System.out.println(dept.toString());
        }*/
        MyDao<Person> deptMyDao = new MyDaoImpl<Person>();
        List<Person> deptList = deptMyDao.queryAll(Person.class);
        for (Person dept : deptList) {
            System.out.println(dept.toString());
        }
    }
}
